const { BrowserWindow } = require('electron')

const getSources = (url) => {
  return new Promise((resolve, reject) => {
    let win = new BrowserWindow({
      width: 500,
      height: 500,
      show: false,
      webPreferences: {
        offscreen: true,
        nativeWindowOpen: true
      }
    })
    win.loadURL(url)

    // 在离屏窗口内容加载完获取窗口title和截屏
    win.webContents.on('did-finish-load', async () => {
      // 获取页面的title
      let title = win.getTitle()

      try {
        let image = await win.webContents.capturePage()
        // Get image as dataURL
        let screenshot = image.toDataURL()
  
        // 返回结果
        resolve({
          title,
          screenshot,
          url
        })
  
        // 重置离线窗口
        win.close()
        win = null
      } catch(err) {
        console.log(err)
      }
    })
  })
}

module.exports = getSources